import 'dart:io';
import 'dart:ui';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'package:sciolto/POJO/pojos.dart';
import 'package:sciolto/api/Common_api.dart';
import 'package:sciolto/api/music.dart';
import 'package:sciolto/util/DBController.dart';
import 'package:sciolto/util/setting.dart';
import 'package:sciolto/widget/custom_widget.dart';
import 'package:sciolto/widget/revolvingWidget.dart';

class MusicPage extends StatefulWidget {

  @override
  State<StatefulWidget> createState() => _MusicPageState();
}

class _MusicPageState extends State<MusicPage> {

  Size _size;

  double _x;

  double _y;

  double _value;

  Song currentSong;

  SongList currentSongList;

  List<Feeling> _listOfFeeling;

  TextEditingController controller;

  FocusNode textFocusNode;

  bool _hasLoaded;

  double get x => _x;

  double get y => _y;

  @override
  void initState() {
    super.initState();

    _confirmCurrentSituation();

    controller = TextEditingController();

    textFocusNode = FocusNode();

    _hasLoaded = false;
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _size ??= CommonApi.initParameter(context);
    _x ??= _size.width / 420;
    _y ??= _size.height / 800;
    final musicState = Provider.of<Music>(context);
    _value = musicState.value;
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        _backgroundImage(),
        GestureDetector(
          onTap: () {
            FocusScope.of(context).requestFocus(FocusNode());
          },
          child: Scaffold(
            resizeToAvoidBottomInset: false,
            backgroundColor: Colors.transparent,
            body: Column(
              children: [
                _titleBar(),
                Expanded(
                  flex: 382,
                  child: _hasLoaded ? LayoutBuilder(
                      builder: (context, constraints) =>
                          _feelingsListView(constraints)) : Container(),
                ),
                Expanded(
                  flex: 618,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      _feelingInput(),
                      _songInfoBar(),
                      Spacer(flex: 1,),
                      Padding(
                        padding: EdgeInsets.symmetric(horizontal: 20 * _y),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.end,
                          children: [
                            _processSlider(),
                            Text(
                              Music().showText,
                              style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 10 * _y
                              ),
                            )
                          ],
                        ),
                      ),
                      _buttonBar()
                    ],
                  ),
                )
              ],
            ),
          ),
        )
      ],
    );
  }

  void _confirmCurrentSituation() {
    currentSong = Music().song;
    currentSongList = PlayList().currentSongList;
    TableConnector connector = TableConnectorFactory.connectWithFeelingTable();
    connector.defaultQuery('parent_song_id = ?', [currentSong.id]).then((
        value) {
      print('value = $value');
      _listOfFeeling =
          value.map((element) => Feeling.fromMap(element)).toList();
      print('listOfFeeling = $_listOfFeeling');
      setState(() {
        _hasLoaded = true;
      });
    });
  }

  Widget _noFeeling() {
    return Container(
      width: double.infinity,
      height: double.infinity,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(10),
        color: Colors.transparent
      ),
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Icon(
              Icons.speaker_notes_outlined,
              color: Colors.white,
            ),
            Text(
                "写下自己的感想吧",
              style: TextStyle(
                color: Colors.white,
                fontSize: 20
              ),
            )
          ],
        ),
      ),
    );
  }

  Widget _titleBar() {
    return Container(
      padding: EdgeInsets.all(10 * _y),
      alignment: Alignment.centerLeft,
      color: Colors.transparent,
      child: IconButton(
        padding: EdgeInsets.all(0),
        iconSize: 50 * _y,
        icon: Icon(Icons.keyboard_arrow_down_rounded),
        color: Colors.white,
        onPressed: _onPressDownArrow,
      ),
    );
  }

  Widget _feelingsListView(BoxConstraints constraints) {
    return Container(
      width: constraints.maxWidth,
      height: constraints.maxHeight,
      padding: EdgeInsets.all(20 * _y),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(10),
        color: Colors.grey.withOpacity(0.3)
      ),
      child: _listOfFeeling.isEmpty ? _noFeeling() : ListView.builder(
          itemCount: _listOfFeeling.length,
          itemBuilder: (context, index) =>
              _feelingsListItem(constraints, context, index)),
    );
  }

  Widget _feelingsListItem(BoxConstraints constraints, BuildContext context,
      int index) {
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 5 * _y),
      child: Card(
        shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(5 * _y)
        ),
        elevation: 10,
        child: Ink(
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(5 * _y),
            color: Colors.grey[50],
          ),
          child: InkWell(
              onLongPress: () {
                _onLongPressedFeeling(index);
              },
              child:Padding(
                padding: EdgeInsets.all(10 * _y),
                child: Text(
                  _listOfFeeling[index].content,
                  style: TextStyle(
                      fontSize: 20 * _y,
                      fontWeight: FontWeight.w500,
                      color: Colors.blueGrey),
                ),
              )
          ),),
      ),
    );
  }

  Widget _feelingInput() {
    return Padding(
        padding: EdgeInsets.symmetric(horizontal: 20 * _y, vertical: 10 * _y),
        child: SizedBox(
            width: _size.width,
            height: 100 * _y,
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                SizedBox(
                  width: _size.width - 40 * _y - 60 * _y,
                  height: 80 * _y,
                  child: TextField(
                    controller: controller,
                    textAlignVertical: TextAlignVertical.center,
                    decoration: InputDecoration(
                        hintText: "写点什么...",
                        hintStyle: TextStyle(
                            color: Colors.grey[50], fontSize: 20 * _y),
                        border: OutlineInputBorder(borderSide: BorderSide.none),
                        contentPadding:
                        EdgeInsets.symmetric(horizontal: 10 * _y)),
                    textInputAction: TextInputAction.done,
                    maxLines: 10,
                    maxLength: 255,
                    style: TextStyle(color: Colors.blueGrey[50], fontSize: 25 * _y),
                    focusNode: textFocusNode,
                    cursorColor: Colors.blueGrey,
                    onEditingComplete: () {
                      textFocusNode.unfocus();
                    },
                  ),
                ),
                IconButton(
                  icon: Icon(Icons.send),
                  color: Colors.grey[50],
                  onPressed: _onPressSendFeeling,
                )
              ],
            )));
  }

  Widget _songInfoBar() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 20 * _y),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        // mainAxisAlignment: MainAxisAlignment.start,
        mainAxisSize: MainAxisSize.max,
        children: [
          Align(
            alignment: Alignment.center,
            child: SizedBox(
              width: currentSong.songName.length * 50 * _y,
              height: 50 * _y,
              child: RevolvingText(
                text: currentSong.songName,
                style: TextStyle(
                    fontSize: 35 * _y,
                    fontWeight: FontWeight.w900,
                    color: Colors.white
                ),
                ratioOfBlank: 0.5,
              ),
            ),
          ),
          Align(
            alignment: Alignment.center,
            child: Text(
              currentSong.singerName,
              style: TextStyle(
                  fontSize: 20 * _y,
                  fontWeight: FontWeight.w300,
                  color: Colors.grey[50]
              ),
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
            ),
          )
        ],
      ),
    );
  }


  Widget _buttonBar() {
    String path;
    switch (PlayList().currentType) {
      case PlayerType.common:
        path = Setting.playListStateCommon;
        break;
      case PlayerType.singleCycle:
        path = Setting.playListStateSingleCycle;
        break;
      case PlayerType.listCycle:
        path = Setting.playListStateListCycle;
        break;
      case PlayerType.random:
        path = Setting.playListStateRandom;
        break;
    }
    return Padding(
      padding: EdgeInsets.fromLTRB(20 * _y, 10 * _y, 20 * _y, 40 * _y),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Expanded(
            flex: 1,
            child: Center(
                child: IconButton(
                  onPressed: _onTappingPlayerType,
                  icon: Image(
                    color: Colors.blueGrey[50],
                    image: AssetImage(path),
                  ),
                )
            ),
          ),
          Expanded(
            flex: 1,
            child: Center(
                child: IconButton(
                  iconSize: 40 * _y,
                  color: Colors.blueGrey[50],
                  padding: EdgeInsets.all(0),
                  icon: Icon(Icons.skip_previous),
                  onPressed: () => _onPressSkipButton(-1),
                )
            ),
          ),
          Expanded(
            flex: 1,
            child: Center(
                child: IconButton(
                  padding: EdgeInsets.all(0),
                  icon: Image(
                    color: Colors.blueGrey[50],
                    image: AssetImage(
                        Music().isPlaying
                            ? "images/pause.png"
                            : "images/play.png"
                    ),
                  ),
                  onPressed: () {
                    setState(() {
                      Music().isPlaying ? Music().pause() : Music().play();
                      // isPlaying = !isPlaying;
                    });
                  },
                )
            ),
          ),
          Expanded(
            flex: 1,
            child: Center(
                child: IconButton(
                  iconSize: 40 * _y,
                  padding: EdgeInsets.all(0),
                  color: Colors.blueGrey[50],
                  icon: Icon(Icons.skip_next),
                  onPressed: () => _onPressSkipButton(1),
                )
            ),
          ),
          Expanded(
            flex: 1,
            child: Center(
                child: IconButton(
                  padding: EdgeInsets.all(0),
                  iconSize: 40 * _y,
                  color: Colors.blueGrey[50],
                  icon: Icon(Icons.menu_open),
                  onPressed: () {
                    CustomWidget.showPlayList(context, _size, _x, _y);
                  },
                )
            ),
          ),
        ],
      ),
    );
  }

  /// 进度条
  Widget _processSlider() {
    return SizedBox(
      height: 25 * _y,
      //width: 300 * _x,
      child: Slider(
        activeColor: Colors.cyan,
        inactiveColor: Colors.blueGrey[50],
        value: _value ?? 0.0,
        onChanged: (v) {
          print('进度条变化到了 $v');
          if (Music().isLoaded) {
            Music().onChangeSlider(v);
          }
        },
        onChangeEnd: (v) {
          if (v >= 1) {
            setState(() {});
          }
        },
      ),
    );
  }

  Widget _backgroundImage() {
    return Container(
      width: _size.width,
      height: _size.height,
      decoration: BoxDecoration(
        image: DecorationImage(
            fit: BoxFit.cover,
            image: currentSongList.resourceType == ImageResourceType.ASSET ?
            AssetImage(currentSongList.imagePath) :
            currentSongList.resourceType == ImageResourceType.NETWORK ?
            NetworkImage(currentSongList.imagePath) :
            FileImage(File(currentSongList.imagePath))
        ),
      ),
      child: ClipRRect( // make sure we apply clip it properly
        child: BackdropFilter( //背景滤镜
          filter: ImageFilter.blur(sigmaX: 20, sigmaY: 20), //背景模糊化
          child: Container(
            alignment: Alignment.center,
            color: Colors.grey.withOpacity(0.2),
          ),
        ),
      ),
    );
  }

  /// 歌单/歌曲操作按钮
  Widget _operationItem(String title, String imagePath,
      VoidCallback onPressed) {
    return Padding(
      padding: EdgeInsets.fromLTRB(10, 10, 10, 5),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          MaterialButton(
              onPressed: onPressed,
              elevation: 10,
              splashColor: Colors.cyan[50],
              height: 45 * _y,
              minWidth: 45 * _y,
              padding: EdgeInsets.all(0),
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(10 * _y)
              ),
              child: SizedBox(
                width: 45 * _y,
                height: 45 * _y,
                child: Image(
                  color: Colors.blueGrey,
                  image: AssetImage(imagePath),
                ),
              )
          ),
          Center(
            child: Text(
              title,
              style: TextStyle(
                  fontSize: 10 * _y,
                  color: Colors.blueGrey
              ),
            ),
          )
        ],
      ),
    );
  }

  void _onPressDownArrow() {
    Navigator.of(context).pop();
  }

  void _onPressSendFeeling() {
    FocusScope.of(context).requestFocus(FocusNode());
    if (controller.text.isNotEmpty) {
      TableConnector connector = TableConnectorFactory.connectWithFeelingTable();
      connector.defaultInsert(Feeling(currentSong.id, controller.text).toMap())
          .then((value) {
        setState(() {
          TableConnector connector = TableConnectorFactory.connectWithFeelingTable();
          connector.defaultQuery('parent_song_id = ?', [currentSong.id]).then((
              value) {
            _listOfFeeling =
                value.map((element) => Feeling.fromMap(element)).toList();
            setState(() {
              _hasLoaded = true;
              controller.text = '';
            });
          });
        });
      });
    } else {
      CustomWidget.showToast("忘记写感想了哦");
    }
  }

  void _onTappingPlayerType() {
    setState(() {
      PlayList().currentType = PlayerType.values[
      (PlayList().currentType.index + 1) %
          PlayerType.values.length];
    });
  }

  // 1 为下一首， -1为上一首
  void _onPressSkipButton(int direction) {
    assert(direction == 1 || direction == -1);
    if (direction == 1) {
      PlayList().setNextSongShouldPlay();
    } else {
      PlayList().setPreviousShouldPlay();
    }
    setState(() {
      _confirmCurrentSituation();
    });
  }

  void _onLongPressedFeeling(index) {
    showModalBottomSheet(
        barrierColor: Colors.transparent,
        backgroundColor: Colors.transparent,
        context: context,
        builder: (context) {
          return Container(
            width: _size.width,
            height: 150 * _y,
            decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(10 * _y)
            ),
            child: Padding(
              padding: EdgeInsets.symmetric(horizontal: 10 * _y),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Expanded(
                    flex: 618,
                    child: LayoutBuilder(
                      builder: (context, constraints) {
                        return SizedBox(
                            width: constraints.maxWidth,
                            height: constraints.maxHeight,
                            child: Row(
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [
                                _operationItem(
                                    "更改内容", "images/change.png", () {
                                  _showModifyFeelingDialog(
                                      _listOfFeeling[index]).then((value) {
                                    Navigator.of(context).pop();
                                  });
                                }),
                                _operationItem("删除", "images/dismiss.png", () {
                                  TableConnector con = TableConnectorFactory.connectWithFeelingTable();
                                  con.defaultDelete(
                                      'id = ?', [_listOfFeeling[index].id])
                                      .then((value) {
                                    Navigator.of(context).pop();
                                  });
                                })
                              ],
                            )
                        );
                      },
                    ),
                  ),
                  Expanded(
                    flex: 1,
                    child: Container(
                        width: _size.width, color: Colors.blueGrey),
                  ),
                  Expanded(
                      flex: 381,
                      child: LayoutBuilder(
                        builder: (context, constraints) {
                          return MaterialButton(
                            onPressed: () {
                              Navigator.of(context).pop();
                            },
                            shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.only(
                                    bottomLeft: Radius.circular(10 * _y),
                                    bottomRight: Radius.circular(10 * _y))
                            ),
                            splashColor: Colors.cyan[50],
                            height: constraints.maxHeight,
                            minWidth: constraints.maxWidth,
                            child: Center(
                              child: Text(
                                "取消",
                                style: TextStyle(
                                    fontSize: 20 * _y,
                                    color: Colors.blueGrey
                                ),
                              ),
                            ),
                          );
                        },
                      )
                  )
                ],
              ),
            ),
          );
        }).then((value1) {
      setState(() {
        TableConnector connector = TableConnectorFactory.connectWithFeelingTable();
        connector.defaultQuery('parent_song_id = ?', [currentSong.id]).then((
            value) {
          _listOfFeeling =
              value.map((element) => Feeling.fromMap(element)).toList();
          setState(() {
            _hasLoaded = true;
          });
        });
      });
    });
  }

  Future<T> _showModifyFeelingDialog<T>(Feeling feeling) {
    return CustomWidget.showCustomDialog(
        context: context,
        barrierDismissible: false,
        builder: (context) {
          TextEditingController controller = TextEditingController();
          FocusNode textFocusNode = FocusNode();
          return GestureDetector(
              behavior: HitTestBehavior.opaque,
              onTap: () {
                FocusScope.of(context).requestFocus(FocusNode());
              },
              child: Material(
                color: Colors.transparent,
                type: MaterialType.transparency,
                child: Padding(
                  padding: EdgeInsets.symmetric(
                    horizontal: 50 * _x,
                    vertical: 255 * _y,
                  ),
                  child: Card(
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(10 * y)
                    ),
                    shadowColor: Colors.blueGrey,
                    color: Colors.white,
                    elevation: 5,
                    child: Column(
                      children: [
                        Padding(
                          padding:
                          EdgeInsets.fromLTRB(20 * y, 20 * y, 20 * y, 0),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              Text(
                                "修改感想",
                                style: TextStyle(
                                    fontSize: 20 * y, color: Colors.blueGrey),
                              ),
                            ],
                          ),
                        ),
                        Padding(
                          padding: EdgeInsets.symmetric(
                              vertical: 20 * _y),
                          child: Container(
                            width: 300 * _x,
                            height: 100 * _y,
                            child: TextField(
                              controller: controller,
                              textAlignVertical: TextAlignVertical.center,
                              decoration: InputDecoration(
                                  hintText: "请输入内容",
                                  hintStyle: TextStyle(color: Colors.grey[300]),
                                  border: OutlineInputBorder(
                                      borderSide:
                                      BorderSide.none),
                                  contentPadding: EdgeInsets.symmetric(
                                      horizontal: 10 * y)),
                              textInputAction: TextInputAction.done,
                              maxLines: 10,
                              maxLength: 255,
                              style: TextStyle(color: Colors.grey),
                              focusNode: textFocusNode,
                              cursorColor: Colors.blueGrey,
                              onEditingComplete: () {
                                textFocusNode.unfocus();
                              },
                            ),
                          ),
                        ),
                        Spacer(
                          flex: 1,
                        ),
                        Row(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            Expanded(
                              flex: 1,
                              child: GestureDetector(
                                  onTap: () {
                                    textFocusNode.unfocus();
                                    Navigator.of(context).pop();
                                  },
                                  child: Container(
                                    height: 50 * y,
                                    alignment: Alignment.center,
                                    decoration: BoxDecoration(
                                        borderRadius: BorderRadius.only(
                                            bottomLeft:
                                            Radius.circular(10 * y)),
                                        border: Border.all(
                                            color: Colors.blueGrey)),
                                    child: Text(
                                      "取消",
                                      style: TextStyle(
                                          fontSize: 20 * y,
                                          color: Colors.blueGrey),
                                    ),
                                  )),
                            ),
                            Expanded(
                              flex: 1,
                              child: GestureDetector(
                                  onTap: () {
                                    if (controller.text.isNotEmpty) {
                                      TableConnector con = TableConnectorFactory.connectWithFeelingTable();
                                      feeling.content = controller.text;
                                      con.defaultUpdate(
                                          feeling.toMap(), 'id = ?',
                                          [feeling.id]).then((value) {
                                        CustomWidget.showToast("修改成功");
                                        Navigator.of(context).pop();
                                      });
                                    } else {
                                      CustomWidget.showToast("感想不能为空哦");
                                    }
                                  },
                                  child: Container(
                                    height: 50 * y,
                                    alignment: Alignment.center,
                                    decoration: BoxDecoration(
                                        borderRadius: BorderRadius.only(
                                            bottomRight:
                                            Radius.circular(10 * y)),
                                        border: Border.all(
                                            color: Colors.blueGrey)),
                                    child: Text(
                                      "确定",
                                      style: TextStyle(
                                          fontSize: 20 * y,
                                          color: Colors.blueGrey),
                                    ),
                                  )),
                            ),
                          ],
                        )
                      ],
                    ),
                  ),
                ),
              ));
        });
  }

}
